{template 'aitimt/common/header'}
<link rel="stylesheet" type="text/css" href="{$aideUrl}app/resource/components/mui/mui.ext.css?v=201802119">
<style type="text/css">
    .mui-bar a{color: #ff9900;}
    .top-return{left: 10px}
    .mui-bar-nav{height:7%;}
    .mui-btn-primary{background-color: #ff9900;}
    .mui-btn-primary:enabled:active{background-color: #ec7230!important;}
    .mui-textarea{ height:auto!important; width:100%;}
    .area {margin: 20px auto 0px auto;}
    .mui-input-group:first-child {margin-top: 20px;}
    .mui-rmb i{ font-style:normal; }
    .mui-input-row label~input, .mui-input-row label~select, .mui-input-row label~textarea {width: 65%;}
    .mui-del{color:#999}
    footer .mui-input-row label{line-height:2!important; padding:11px 0; text-align:right; float:right;}
    footer .mui-input-row span{line-height:1.7; padding:11px 10px 11px 0;}
    footer .mui-input-row .mui-btn{top: 0; font-size:16px;line-height:1.6!important;border-radius:0; width:35%}
    .mui-input-row #get_code{width:auto; border-radius: 0;line-height: 1.7;}
    .mui-help-top .mui-table-view-cell{padding: 9px 12px;}
    .mui-help-top .mui-icon-help:before{ color:#fe5001; font-size:18px;}
    .mui-help-top .mui-small{ font-size:90%!important;}
    .mui-help-top .mui-help-info:before{position: absolute;content: ""; height:99%!important;left:0;top:0;width:3px; background-color:#fe5001;}
    .mui-input-row.mui-help .mui-help-info{padding-right:30px;}
    [data-type=date] .mui-dtpicker-title h5, [data-type=date] .mui-picker{width: 20%!important;}
    .mui-dtpicker-title h5,.mui-picker{ display:inline-block!important;}
    .mui-popover{position: fixed;}
    .mui-content{background: white;}
    .mui-input-row label~input, .mui-input-row label~select, .mui-input-row label~textarea{width: 50%;font-size: 15px;}
    .mui-input-row label{width: 45%;font-size: 15px;}
    .certificate, .report{position: absolute;left: 5%;top: 30%;}
    #certificate, #report{position: absolute;opacity: 0;}

</style>
<header class="mui-bar mui-bar-nav">
    <a class="top-return mui-action-back"><img src="{$aideUrl}app/resource/aitimt/images/return.png" ></a>
    <a class="top-logo"><img src="{$aideUrl}app/resource/aitimt/images/logo.png" ></a>
    <!--公共菜单start -->
    {template 'aitimt/common/menu'}
    <!-- 公共菜单end-->
</header>
<form id="formdata" action="" method="post" onSubmit="return check(this)" enctype="multipart/form-data" style="position: initial">
    <input type="hidden" id="fid" name="fid" value="{$fid}" />
    <div class="mui-content">
        <div class="mui-card-header mui-card-media" style="padding-bottom:10px;background:#ffffff">
        </div>

        <div class="mui-content-padded">
            <p>基本信息</p>
        </div>
        <div class="mui-input-group">
            <div class="mui-input-row">
                <label>昵称</label>
                <input type="text" name="form[remarks]" id="remarks" placeholder="(必填)" value="{$form['remarks']}">
            </div>
            <div class="mui-input-row">
                <label>姓名</label>
                <input type="text" name="form[realname]" id="realname" placeholder="(必填)" value="{$form['realname']}">
            </div>
            <div class="mui-input-row mui-help">
                <label>手机</label>
                <input type="number" name="form[mobile]" id="mobile" placeholder="(必填)" pattern="[0-9]*" value="{$form['mobile']}"/>
            </div>
            <div class="mui-input-row">
                <label> 性别</label>
                {php echo tpl_app_fans_form('gender', $form['gender'], $placeholder);}
            </div>
            <div class="mui-input-row">
                <label> 邮箱</label>
                <input type="text" name="form[email]" value="{$form['email']}" id="email" placeholder="必填">
            </div>
            <div class="mui-input-row">
                <label> 证件号</label>
                <input type="text" name="form[idcard]" value="{$form['idcard']}" id="idcard" placeholder="(必填)">
            </div>
            <div class="mui-input-row">
                <label> 联系地址</label>
                <input type="text" name="form[address]" id="address" placeholder="(必填)" value="{$form['address']}">
            </div>
            <div class="mui-input-row">
                <label> 紧急联系人</label>
                <input type="text" name="form[emerperson]" id="emerperson" placeholder="(必填)" value="{$form['emerperson']}">
            </div>
            <div class="mui-input-row">
                <label> 紧急联系人手机</label>
                <input type="text" name="form[emerphone]" id="emerphone" placeholder="(必填)" value="{$form['emerphone']}">
            </div>
            <div class="mui-input-row">
                <label> 出生日期</label>
                {php echo tpl_app_fans_form('birth', array('year' => $form['birthyear'], 'month' => $form['birthmonth'], 'day' => $form['birthday']), $placeholder);}
            </div>
            <div class="mui-input-row">
                <label> 省市区</label>
                {php echo tpl_app_fans_form('reside', array('province' => $form['resideprovince'], 'city' => $form['residecity'], 'district' => $form['residedist']), $placeholder);}
            </div>

            <div class="mui-input-row">
                <label>血型</label>
                {php echo tpl_app_fans_form('bloodtype', $form['bloodtype'], $placeholder);}
            </div>
            <div class="mui-input-row">
                <label> 衣服尺寸</label>
                <input type="text" name="form[size]" placeholder="请填写尺寸" value="{$form['size']}">
            </div>
            <div class="mui-input-row">
                <label> 学历</label>
                {php echo tpl_app_fans_form('education',$form['education'],$placeholder);}
            </div>
            <div class="mui-input-row" style="height: 5.5rem;border-bottom: 1px solid #EEEEEE">
                <label> 一年内完赛证书</label>
                <div class="certificate">
                    <input  type="file" name="certificate" id="certificate" onchange="Upload(1);" accept="image/*" multiple="multiple"/>

                    <img id="certificate-img" src="{if $form['certificate']}{$form['certificate']}{else}{$aideUrl}app/resource/aitimt/images/positive.png{/if}" style="width: 100px;" >
                    <div id="certificate-message"></div>
                </div>

            </div>
            <div class="mui-input-row" style="height: 5.5rem;border-bottom: 1px solid #EEEEEE">
                <label> 体检证明</label>
                <div class="certificate">
                    <input  type="file" name="report" id="report" onchange="Upload(2);" accept="image/*"  multiple="multiple"/>
                    <img id="report-img" src="{if $form['report']}{$form['report']}{else}{$aideUrl}app/resource/aitimt/images/positive.png{/if}" style="width: 100px;" >
                    <div id="report-message"></div>
                </div>
            </div>
        </div>

        </div>
    <input type="submit" class="mui-btn mui-btn-orange mui-btn-block" name="submit" value="提交" />
</form>
<script type="text/javascript">
            $(document).ready(function(){
        });
    function Upload(id) {
        var fid = $("#fid").val();
    if (id==1) {
        var $pic = document.querySelector("#certificate");//上传出发按钮
        var $img = document.querySelector("#certificate-img");
        var $type='certificate';
        var message= document.getElementById('certificate-message');
    }else {
        var $pic = document.querySelector("#report");//上传出发按钮
        var $img = document.querySelector("#report-img");
        var $type='report';
        var message= document.getElementById('report-message');
    }
        var file = $pic.files[0];//获取file对象单张
        var reader = new FileReader();//创建filereader对象
        reader.readAsDataURL(file);//转换数据
        reader.onload = function (e) {//加载ok时触发的事件
        $img.removeAttribute("src");
            $img.setAttribute("src", e.target.result);
        };
        var html='';
        $.ajaxFileUpload({
            type: "POST",
            url: "{php echo app_url('home/index/imagesajax')}",
            data:{fid:fid,type:$type,source:'common'},
            fileElementId:$type,//文件选择框的id属性
            secureuri : false,//是否启用安全提交，默认为false
            dataType: 'json',//服务器返回的格式
            async : false,
            success: function(res){
                if(res.errno==0){
                    $("#fid").attr("value", res.data.fid);
                }else{
                    html = "<p style='color:#d06f6f'>" + res.errmsg + "</p>";
                    message.innerHTML=html;
                }
            },
            error: function (data, status, e){
                console.log(2)
            }
        });
    };
    mui('.mui-scroll-wrapper').scroll();
    //省级地址码校验
    var checkProv = function (val) {
        var pattern = /^[1-9][0-9]/;
        var provs = {11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门"};
        if(pattern.test(val)) {
            if(provs[val]) {
                return true;
            }
        }
        return false;
    }
    //出生日期码校验
    var checkDate = function (val) {
        var pattern = /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
        if(pattern.test(val)) {
            var year = val.substring(0, 4);
            var month = val.substring(4, 6);
            var date = val.substring(6, 8);
            var date2 = new Date(year+"-"+month+"-"+date);
            if(date2 && date2.getMonth() == (parseInt(month) - 1)) {
                return true;
            }
        }
        return false;
    }
    //校验码校验
    var checkCode = function (val) {
        var p = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
        var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
        var code = val.substring(17);
        if(p.test(val)) {
            var sum = 0;
            for(var i=0;i<17;i++) {
                sum += val[i]*factor[i];
            }
            if(parity[sum % 11] == code.toUpperCase()) {
                return true;
            }
        }
        return false;
    }
    //身份证规则校验
    var checkID = function (val) {
        if(checkCode(val)) {
            var date = val.substring(6,14);
            if(checkDate(date)) {
                if(checkProv(val.substring(0,2))) {
                    return true;
                }
            }
        }
        return false;
    }
    //数据发送
    function postData(){
        $.post("{php echo app_url('home/index/mycommonedit')}", $("#formdata").serialize(), function(data){
           console.log(data);
            if(data.errno == 0){
                var btnArray = ['确定'];
                var msg='编辑成功';
                mui.confirm(msg,'',btnArray, function(e) {
                    location.href = "{php echo app_url('home/index/mycommon')}";
                });
            }else{
                mui.toast('服务器错误！');
            }
        },"json");
    }

    //校验表单
    function check(form) {
        var patt = new RegExp(/\s+/g);
        var checksubmit = false,value='';
        if ($.trim(form['form[remarks]'].value) == '') {
            mui.toast('请输入昵称')
            $(form['form[remarks]']).focus();

            return false;
        }
            if ($.trim(form['form[realname]'].value) == '') {
                    mui.toast('请输入姓名')
                    $(form['form[realname]']).focus();

                return false;
            }
            if (!form['form[mobile]'].value) {
                mui.toast('请输入手机号');
                    $(form['form[mobile]']).focus();
                return false;
            }else{
                var mobile = $('#mobile').val();
                var pattern = /^1[0-9]{10}$/;

                if (!pattern.test(mobile)) {
                    mui.toast('手机号不合法');
                        $(form['form[mobile]']).focus();
                    return false;
                }
            }
        var  email=document.getElementById('email');
        if (!email.value) {
            $(form['form[email]']).focus();
            mui.toast('请输入邮箱');
            return false;
        }else {
            var emailreg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
            if (emailreg.test(email.value))
            {
            }else {
                $(form['form[email]']).focus();
                mui.toast('请输入正确的邮箱');
                return false;
            }
        }
        var  card=document.getElementById('idcard');
        if (!card.value) {
            $(form['form[idcard]']).focus();
            mui.toast('请输入证件号');
            return false;
        }else {
            var userCardvalue = card.value;//获取输入身份证
            var userCardreg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            var taiwanreg=/^[A-Z][0-9]{9}$/;
            var xianggangreg=/^[A-Z][0-9]{6}\([0-9A]\)$/;
            var aomenreg=/^[157][0-9]{6}\([0-9]\)$/;
            if(userCardreg.test(userCardvalue)||taiwanreg.test(userCardvalue)||xianggangreg.test(userCardvalue)||aomenreg.test(userCardvalue))
            {
            }else {
                $(form['form[idcard]']).focus();
                mui.toast('请输入正确的证件号码');
                return false;
            }
        }
        if ($.trim(form['form[address]'].value) == '') {
            mui.toast('请输入联系地址');
                $(form['form[address]']).focus();
            return false;
        }
        if ($.trim(form['form[emerperson]'].value) == '') {
            mui.toast('请输入紧急联系人');
                $(form['form[emerperson]']).focus();
            return false;
        }
        if (!form['form[emerphone]'].value) {
            mui.toast('请输入紧急联系人手机');
                $(form['form[emerphone]']).focus();
            return false;
        }else{
            var mobile = $('#emerphone').val();
            var pattern = /^1[0-9]{10}$/;

            if (!pattern.test(mobile)) {
                mui.toast('手机号不合法');
                    $(form['form[emerphone]']).focus();
                return false;
            }
        }
            if($(form['essential']).length){
                $(form['essential']).each(function(){
                    var inputkey = $(this).val();
                    var formtype = $(this).data('type');
                    var inputName = 'form_item_val_'+$(this).val();
                    if (inputkey!=''){
                        if ($(form[inputName+'[]']).length || formtype=='6'){
                            inputName = inputName+'[]';
                            if ($(form[inputName]).attr("type")=='checkbox' && $('input:checkbox[name="'+inputName+'"]:checked').length == 0) {
                                util.alert($(this).attr("title")+'为必选项', ' ', function() {
                                    $(form[inputName]).focus();
                                });
                                checksubmit = false;
                                return false;
                            }else if(formtype=='6' && !$(form[inputName]).length){
                                util.alert($(this).attr("title")+'不能为空', ' ', function() {});
                                checksubmit = false;
                                return false;
                            }
                        }else if($(form[inputName+'[province]']).length){
                            if (!form[inputName+'[province]'].value) {
                                util.alert($(this).attr("title")+'为必选项', ' ', function() {
                                    $('.mui-district-picker-'+inputName).trigger('tap');
                                });
                                checksubmit = false;
                                return false;
                            }
                        }else{
                            if ($.trim(form[inputName].value)=="" && $(form[inputName]).attr("type")!='radio' && !$(form[inputName]).next().val()) {
                                var msg = $(form[inputName]).siblings('.mui-calendar-picker'+inputkey).length?'为必选项':'不能为空';
                                util.alert($(this).attr("title")+msg, ' ', function() {
                                    if (formtype=='3' || formtype=='4'){
                                        $(form[inputName]).focus();
                                    }
                                    $(form[inputName]).siblings('.mui-calendar-picker'+inputkey).trigger('tap')
                                    $(form[inputName]).trigger('tap');
                                });
                                checksubmit = false;
                                return false;
                            }else if($(form[inputName]).attr("type")=='radio' && $('input:radio[name="'+inputName+'"]:checked').length == 0){
                                util.alert($(this).attr("title")+'为必选项', ' ', function() {
                                    $(form[inputName]).focus();
                                    $(form[inputName]).trigger('tap');
                                });
                                checksubmit = false;
                                return false;
                            }
                        }
                    }else{
                        inputName = "member["+formtype+"]";
                        var typeStr = "education,birthyear,resideprovince,constellation,zodiac,bloodtype";
                        if (typeStr.indexOf(formtype)>-1){
                            if (formtype=='birthyear' && $(form['birth']).val()==""){
                                util.alert($(this).attr("title")+'为必选项', ' ', function() {
                                    $(form['birth']).trigger('tap');
                                });
                                checksubmit = false;
                                return false;
                            }else if(formtype=='resideprovince' && $('.mui-district-picker-reside').val()==""){
                                util.alert($(this).attr("title")+'为必选项', ' ', function() {
                                    $('.mui-district-picker-reside').trigger('tap');
                                });
                                checksubmit = false;
                                return false;
                            }else if ($(form[formtype]).val()==""){
                                util.alert($(this).attr("title")+'为必选项', ' ', function() {
                                    $(form[formtype]).siblings('.mui-'+formtype+'-picker').trigger('tap');
                                });
                                checksubmit = false;
                                return false;
                            }
                        }else if($.trim($(form[inputName]).val())=="" && $(form[inputName]).length){
                            util.alert($(this).attr("title")+'不能为空', ' ', function() {
                                $(form[inputName]).focus();
                            });
                            checksubmit = false;
                            return false;
                        }else{
                            var pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;

                            if (formtype == 'idcard' && !pattern.test($(form[inputName]).val())){
                                util.alert($(this).attr("title")+'不合法', ' ', function() {
                                    $(form[inputName]).focus();
                                });
                                checksubmit = false;
                                return false;
                            }

                            if( formtype == 'idcard'){
                                var id_card = $(form[inputName]).val();
                                if(checkID(id_card) == false){
                                    util.alert($(this).attr("title")+'不合法', ' ', function() {
                                        $(form[inputName]).focus();
                                    });
                                    checksubmit = false;
                                    return false;
                                }
                            }

                        }
                    }
                    checksubmit = true;
                });
            }else{
                checksubmit = true;
            }

        if (checksubmit){
                $.ajax({
                    type: 'POST',
                    url: "{php echo app_url('home/join/validquota',array('activityid'=>$activityid,'optionid'=>$optionid))}&teamnum=" + $('.js-pay-team').val(),
                    dataType: 'json',
                    async:false,
                    success: function(data){
                        if(!data.errno){
                            checksubmit = true;
                        }else{
                            checksubmit=false;
                            setTimeout(function() {
                                util.alert(data.message, ' ', function() {return false;});
                            },450);
                        }
                    },
                    error:function(){
                        checksubmit=false;
                        setTimeout(function() {
                            util.alert('服务器加载错误, 请联系主办方', ' ', function() {return false;});
                        },450);
                    }
                });
            }
            if (checksubmit){
                {if $activity['costcredit']}
                util.confirm("参与当前活动需要消耗 {$activity['costcredit']} 积分", ' ',['取消', '确认'], function(e) {
                    if (e.index == 1){
                        postData();
                    }
                });
                {else}
                postData();
                {/if}
                }
                return false;
            }

            {if $_W['container']=='wechat'}
            var appid = '{$_W['account']['jssdkconfig']['appId']}';
            var timestamp = '{$_W['account']['jssdkconfig']['timestamp']}';
            var nonceStr = '{$_W['account']['jssdkconfig']['nonceStr']}';
            var signature = '{$_W['account']['jssdkconfig']['signature']}';

            wx.config({
                debug: false,
                appId: appid,
                timestamp: timestamp,
                nonceStr: nonceStr,
                signature: signature,
                jsApiList: ['checkJsApi','chooseImage','previewImage','uploadImage','downloadImage']
            });

            wx.ready(function(){
                // 5 图片接口
                var images = {
                    localId: [],
                    serverId: []
                };
                document.querySelector('#chooseImage').onclick = function () {
                    wx.chooseImage({
                        count: 1,
                        success: function (res) {
                            images.localId = res.localIds;
                            //alert('已选择 ' + res.localIds.length + ' 张图片');
                            $(function(){
                                var imglist = "";
                                $.each(res.localIds, function(i, n){
                                    imglist+='<li ><img src="'+n+'" style="height:150px;" /></li>';
                                    //$("#errormsg").append("res.localIds:"+n+"<br />");
                                });
                                $("#imageContainer > ul").html(imglist);
                                $("#chooseImage").removeClass("mui-btn-success");
                                $("#chooseImage").addClass("mui-btn-orange");
                                $("#chooseImage").text("更换图片");
                            });
                            uploadimg(images.localId);
                        }
                    });
                };

                function uploadimg(localIds){
                    //$("#errormsg").append("<br />localIds length:"+localIds.length);
                    var localId = localIds.pop();
                    wx.uploadImage({
                        localId: localId,
                        //isShowProgressTips: 1,
                        success: function (res) {
                            images.serverId = []; //把值清空掉，只需一个
                            images.serverId.push(res.serverId);
                            //$("#errormsg").append("<br />"+res.serverId+",");
                            if(localIds.length > 0){
                                uploadimg(localIds);
                            }
                            else{
                                if(window.XMLHttpRequest){
                                    xmlHttpRequest=new XMLHttpRequest();
                                }else{
                                    xmlHttpRequest=new ActiveXObject("MSXML2.XMLHTTP.3.0");//("Microsoft.XMLHTTP");
                                }
                                //$("#errormsg").append("<br />准备处理，请等待...");
                                serverIds=images.serverId;
//                        document.getElementById("serverIds").value = JSON.stringify(serverIds);
                                document.getElementById("serverIds").value = serverIds[0];
                                //$("#serverIds").val(JSON.stringify(serverIds));
                                //getimgtoserver(serverIds);
                            }
                        },
                        fail: function (res) {
                            console.log(JSON.stringify(res));
                            alert("上传失败，请稍候重试");
                        }
                    });
                }
            });
            {/if}
</script>
</body>
</html>
